﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using System.IO.Compression;

namespace shop.Web.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AppController : ControllerBase
    {

        private IWebHostEnvironment _hostEnvironment;
        private readonly ILogger _logger;

        public AppController(IWebHostEnvironment hostEnvironment, ILogger<AppController> logger)
        {
            _hostEnvironment = hostEnvironment;
            _logger = logger;
        }



        /// <summary> 上传客户端安装包 </summary>
        [HttpPost]
        [RequestSizeLimit(1000_000_000)]
        public async Task<JsonResult> UploadClient([Required] IFormCollection form)
        {
            var webRootPath = _hostEnvironment.ContentRootPath; //>>>相当于HttpContext.Current.Server.MapPath("") 
            var dir = Path.Combine(webRootPath, "publishUpload");   //上传发布文件的临时目录
            if (!Directory.Exists(dir))
            {
                new DirectoryInfo(dir).Create();
            }

            form.TryGetValue("app", out var app);
            var file = form.Files.FirstOrDefault(); //文件

            if (file == null || string.IsNullOrEmpty(app) )
            {
                return new JsonResult(new { isOk = false, message = "参数不正确" });
            }


            var completeFilePath = Path.Combine(dir, app.ToString()); //实际上传目标文件路径

            using (var fs = System.IO.File.Create(completeFilePath))
            {
                await file.CopyToAsync(fs);
                await fs.FlushAsync();
            }


            // 给用户下载的publish路径
            var publishDir = Path.Combine(webRootPath, "publish", app.ToString());   //上传发布文件的临时目录


            //解压到目标文件夹
            int c = 3;  //最多重试3次
            bool isok = false;
            string err = string.Empty;
            while (c > 0)
            {
                try
                {
                    await Task.Run(() =>
                    {
                        ZipFile.ExtractToDirectory(completeFilePath, publishDir.ToString(), true);
                    });
                }
                catch (Exception ex)
                {
                    err = "解压文件异常:" + completeFilePath + " => " + publishDir + ", " + ex.Message;
                    _logger.LogError("解压文件异常:" + completeFilePath + " => " + publishDir, ex);
                    c--;
                    continue;
                }

                _logger.LogInformation($"部署:{app}, 目录{publishDir}, 成功");
                isok = true;
                break;
            }

            if (isok)
            {
                return new JsonResult(new { isOk = isok, message = "$部署:{app}, 目录{appDir}, 成功" });
            }
            else
            {
                return new JsonResult(new { isOk = isok, message = err });
            }
        }



    }
}
